<template>

	<view class="page">
		<l-file ref="lFile" :logo="logo" @up-success="onSuccess"></l-file>
		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<mpopupHeaderItem label="企业名称" :value="equipment.operatorName" height="90px" />

<mpopupHeaderRadioItem label="统一社会信用代码" :custom-class="'custom-align'" height="90px"
					:custom-style="{ padding: '20rpx' }">
					<input class="centered-input" v-model="equipment.sociaCreditCode" placeholder="请输入组别号" />
				</mpopupHeaderRadioItem>
				
				
		

			</mpopupHeaderRadioItem>
			<mpopupHeaderRadioItem label="法定代表人" height="90px">
					<input class='centered-input' v-model="equipment.legalRepresentative" placeholder="请输入法定代表人" />
			</mpopupHeaderRadioItem>
			<mpopupHeaderItem label="经营场所" :value="equipment.operatorPlace" height="90px" />
			<mpopupHeaderItem label="库房地址" :value="equipment.address" height="90px" />
			<mpopupHeaderRadioItem label="经营方式" :custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }">
				<!-- 自定义右侧内容 -->
				<template>

					<uni-data-checkbox v-model="equipment.modeOfOperation" selectedColor="blue" selectedTextColor="blue"
						mode='list' :localdata="operationList" @change="modeChange"></uni-data-checkbox>
				</template>
			</mpopupHeaderRadioItem>

			<mpopupHeaderRadioItem label="检查日期" :custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }">
				<!-- 自定义右侧内容 -->
				<template #default="{ value }">
					<uni-datetime-picker v-model="equipment.checkDate" type="date" @change="handleCheckDateChange" />
				</template>
			</mpopupHeaderRadioItem>

			<mpopupHeaderRadioItem label="检查内容" :custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }">
				<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list' :localdata="contextList"
					v-model="equipment.medicalCheckContext"></uni-data-checkbox>
			</mpopupHeaderRadioItem>

			<mpopupHeaderRadioItem label="检查类型" :custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }">
				<!-- 自定义右侧内容 -->
				<template #default="{ value }">
					<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" :localdata="typeList" mode='list'
						v-model="equipment.medicalCheckType"></uni-data-checkbox>
				</template>
			</mpopupHeaderRadioItem>

			<mpopupHeaderRadioItem label="检查依据" :custom-class="'custom-align'" :show-bottom-border="true"
				:custom-style="{ padding: '20rpx' }">
				<!-- 自定义右侧内容 -->
				<template #default="{ value }">
					<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list' :localdata="toList"
						v-model="equipment.medicalCheckTo"></uni-data-checkbox>
				</template>
			</mpopupHeaderRadioItem>



		</uni-card>
		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<view class="card-title">不符合项目</view>
			<view class="table-container">
				<uni-table border empty-text="暂无验证记录">
					<uni-tr style="background-color: #e9f1fe">
						<uni-th width="15%" align="center">序号</uni-th>
						<uni-th width="30%" align="center">不符合项条款号(关键项目前加*)</uni-th>
						<uni-th width="35%" align="center">不符合项描述</uni-th>
						<uni-th width="20%" align="center">附件</uni-th>
					</uni-tr>
					<!-- 不符合项目表格 -->
					<uni-tr v-for="(item,index) in verifyRecords" :key="index">
						<uni-td style="height: 50px;" align="center">{{ index + 1 }}</uni-td> <!-- 序号 -->
						<uni-td align="center">{{ item.clause }}</uni-td> <!-- 条款号 -->
						<uni-td align="center">
							<view class="clickable-cell" @click="editDescription(index)">
								{{ item.remarks || '点击添加备注' }}
							</view>
						</uni-td>
						<uni-td align="center">
							<view class="clickable-cell" @tap="onUpload(index)">
								{{ getFileName(item.fileInfo)  || '点击上传' }}
							</view>
						</uni-td></uni-tr>
				</uni-table>
			</view>
			<!-- 添加更多 -->
			<view class="dashed" @click="showRolePicker">
				<text style="font-size: 20rpx;">+点此添加更多不符合项目</text>
			</view>
		</uni-card>


		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<view class="card-title">合理缺项</view>
			<view class="table-container">
				<uni-table border empty-text="暂无验证记录">
					<uni-tr style="background-color: #e9f1fe">
						<uni-th width="15%" align="center">序号</uni-th>
						<uni-th width="30%" align="center">合理缺项条款号(关键项目前加*)</uni-th>
						<uni-th width="35%" align="center">合理缺项描述</uni-th>
						<uni-th width="20%" align="center">附件</uni-th>
					</uni-tr>
					<!--合理缺项目表格 -->
					<uni-tr v-for="(item,index) in reasonableList" :key="index">
						<uni-td style="height: 50px;" align="center">{{ index + 1 }}</uni-td> <!-- 序号 -->
						<uni-td align="center">{{ item.clause }}</uni-td> <!-- 条款号 -->
						<uni-td align="center">
							<view class="clickable-cell" @click="editDescription2(index)">
								{{ item.remarks || '点击添加备注' }}
							</view>
						</uni-td>
						<uni-td align="center">
							<view class="clickable-cell" @tap="onUpload2(index)">
								{{ getFileName(item.fileInfo)  || '点击上传' }}
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
			</view>

			<view class="dashed2" @click="showHePicker">
				<text style="font-size: 20rpx;">查看/新增合理缺项</text>
			</view>
		</uni-card>


		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<view class="card-title">不符合项目总览</view>
			<view class="table-container2">
				<uni-table border>

					<uni-tr v-for="(item,index) in processedData" :key="index">
						<!-- 项目列（带合并） -->
						<uni-td style=" width: 120px;  background-color:#e9f1fe;height: 100px;" :rowspan="item.rowspan"
							v-if="item.rowspan > 0">
							{{ item.项目 }}
						</uni-td>

						<!-- 关键项 -->
						<uni-td style=" width: 90px;  background-color:#e9f1fe;height: 100px;">{{ item.关键项 }}</uni-td>

						<!-- 结果 -->
						<uni-td>{{ item.结果 }}</uni-td>
					</uni-tr>
				</uni-table>
			</view>


		</uni-card>

		<!--
		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<signSection2 :initial-list="signList" :initial-date="checkDate" @update:signList="handleSignListUpdate"
				@close="closeDatePopup" @date-change="handleDateChange"></signSection2>
		</uni-card>
-->
		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<view class="card-title">检查组成员签字</view>
			<!-- 虚线容器 -->
			<view class="dashed-box2">
				<view class="custom-title">
					<view
						style="width:150px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:10px;">
						组长签名
					</view>
					<signInput :initialImage="equipment.groupLeaderSign" bgColor="#ffffff" :action="action"
						@signToUrl="signToUrl"></signInput>
				</view>
				<view class="custom-title">
					<view
						style="width:150px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:10px;">
						组员签名
					</view>

					<signInput :initialImage="equipment.teamMemberslSign" bgColor="#ffffff" :action="action"
						@signToUrl="signToUrl2"></signInput>
				</view>
				<view class="custom-title">
					<view
						style="width:150px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:10px;">
						观察员签名
					</view>

					<signInput :initialImage="equipment.observerSign" bgColor="#ffffff" :action="action"
						@signToUrl="signToUrl3"></signInput>
				</view>

				<!-- 动态签名列 -->
				<view v-for="(sign, index) in equipment.workOrderSignatureList" :key="index" class="custom-title">
					<view
						style="width:150px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:10px;">
						{{sign.signaturePosition}}
					</view>

					<signInput :initialImage="sign.signature" bgColor="#ffffff" :action="action"
						@signToUrl="(url) => handleSignUpload(url, index)"></signInput>
				</view>

				<!-- 添加签名列按钮 -->
				<view class="dashed-box3" @click="addSignColumn">
					<text style="font-size: 20rpx;font-weight: bold;">+点此添加更多签字栏</text>
				</view>


			</view>
		</uni-card>



		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<view class="card-title">经营企业确认检查结果</view>
			<!-- 虚线容器 -->
			<view class="dashed-box2">
				<view class="custom-title">
					<view
						style="width:150px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:20px;">
						企业负责人签字
					</view>

					<signInput :initialImage="equipment.enterpriseSign" bgColor="#ffffff" :action="action"
						@signToUrl="signToUrl4"></signInput>
				</view>


				<!-- 企业确认日期 -->
				<view class="custom-dateText">
					<text @click="openDatePicker" class="custom-text3">{{ this.equipment.enterpriseDate || '选择日期' }}</text>
				</view>

			</view>

			<!-- 虚线容器 -->
			<view class="dashed3">
				<!-- 标题行 -->
				<view class="title-row2">
					<text class="title">珠海市食品药品（医疗器械）审评认证中心（盖章）</text>
					<view class="edit-btn" @click="handleSign(item.type)">
						<evan-checkbox v-model="checked">是否启用电子签章功能</evan-checkbox>
					</view>
				</view>

				<view class="dashed4">
					<text style="font-size: 20rpx;font-weight: bold;">+点此签章（部门公章）</text>
				</view>
			</view>

			<view>
				<uni-title type="h1" align="center" title="备注"></uni-title>
				<view class="uni-column">
					<textarea v-model="equipment.remark" placeholder="请填写相关内容" />
				</view>
			</view>
		</uni-card>
		<view>
			<button type="primary" @click="submitForm('1')"> 保存并提交检查报告</button>
			<button style="margin-top: 10px;margin-bottom: 10px;" type="primary" @click="submitForm('0')">暂存</button>
		</view>
		<view>



			<!-- 添加日期选择弹窗 -->
			<uni-popup ref="datePopup" type="dialog">
				<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
					<uni-datetime-picker type="date" @change="handleDateChange" />
				</uni-popup-dialog>
			</uni-popup>

			<!-- 在template中添加 -->
			<uni-popup ref="termPopup" type="center" :mask-click="false">
				<view class="custom-popup">
					<!-- 选择区域 -->
					<view class="selector-box">
						<!-- 修改uni-data-select组件的事件绑定 -->
						<uni-data-select v-model="selectedTerm" :localdata="termList" @change="handleTermChange">
							<!-- 这里显式传递$event -->
						</uni-data-select>
					</view>

					<!-- 动态表格区域 -->
					<view v-if="selectedTerm" class="table-container">
						<uni-table border class="term-table">
							<uni-tr>
								<uni-th width="10%" align="center">章节</uni-th>
								<uni-th width="65%" align="center">条款</uni-th>
								<uni-th width="10%" align="center">内容</uni-th>
								<!--<uni-th width="15%" align="center">不符合项描述</uni-th>-->
							</uni-tr>
							<uni-tr v-for="(item, index) in filteredData" :key="index">
								<uni-td align="center">{{ item.term }}</uni-td>
								<uni-td align="center">{{ item.title }}</uni-td>
								<uni-td>
									<scroll-view scroll-y style="max-height: 200rpx;">
										{{ item.context }}
									</scroll-view>
								</uni-td>
								<!--
								<uni-td>
									{{item.remarks}}
								</uni-td>-->
							</uni-tr>
						</uni-table>

					</view>
					<!-- 操作按钮 -->
					<view class="action-buttons">
						<button class="btn submit" @click="handleSubmit">保存并提交</button>
						<button class="btn cancel" @click="handleCancel">取消</button>
					</view>
				</view>
			</uni-popup>

			<!-- 在template中添加 -->
			<uni-popup ref="hePopup" type="center" :mask-click="false">
				<view class="custom-popup">
					<!-- 选择区域 -->
					<view class="selector-box">
						<!-- 修改uni-data-select组件的事件绑定 -->
						<uni-data-select v-model="selectedTerm" :localdata="termList" @change="handleTermChange">
							<!-- 这里显式传递$event -->
						</uni-data-select>
					</view>
					<!-- 动态表格区域 -->
					<view v-if="selectedTerm" class="table-container">
						<uni-table border class="term-table">
							<uni-tr>
								<uni-th width="10%" align="center">章节</uni-th>
								<uni-th width="65%" align="center">条款</uni-th>
								<uni-th width="10%" align="center">内容</uni-th>

							</uni-tr>
							<uni-tr v-for="(item, index) in filteredData" :key="index">
								<uni-td align="center">{{ item.term }}</uni-td>
								<uni-td align="center">{{ item.title }}</uni-td>
								<uni-td>
									<scroll-view scroll-y style="max-height: 200rpx;">
										{{ item.context }}
									</scroll-view>
								</uni-td>
							</uni-tr>
						</uni-table>

					</view>
					<!-- 操作按钮 -->
					<view class="action-buttons">
						<button class="btn submit" @click="handleHeSubmit">追加更多合理缺项</button>
						<button class="btn cancel" @click="handleCancel">取消</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import SignSection from "@/components/signature-box/signature-box.vue"
	import signSection2 from '@/components/signature-box2/signature-box.vue'
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import mpopupTable from "@/components/mpopup-table.vue"
	import {
		getformat,
		getProject,
		addMedical,
		getMedicalDict,
		addResultList,
		medicalGetInfo,
		medicalUpdate
	} from '@/api/order'
	import {
		getFoodReport
	} from '@/api/report.js'
	export default {
		components: {
			signSection2,
			signInput,
			mpopupHeaderRadioItem,
			mpopupHeaderItem, // 需先导入组件
			mpopupTable,
			SignSection
		},
		data() {
			return {
				fileName: '',
				fileUrl: '',
				currentItem: null,
				action: "https://8954wg323mw0.vicp.fun/app/upload/imageFile", //上传服务器的地址
				medicalCheckContext: '', //检查内容
				medicalCheckType: '', //检查类别
				medicalCheckTo: '', //检查依据
				termList: [], // 选择框选项
				selectedTerm: '', // 当前选中项
				rawData: [], // 原始数据
				filteredData: [], // 过滤后数据
				parentSignList: [],
				reasonableList: [], //符合
				signList: [], // 格式：[{role: 1, signUrl: ''}, ...]
				verifyRecords: [], // 不符合：
				checkDateBox: '',
				checkDate: {
					year: '',
					month: '',
					day: ''
				},
				operationList: {},
				contextList: {},
				typeList: {},
				toList: {},
				currentDate: '',
				equipment: {
					workOrderSignatureList: [],
					reasonableKey: '0',
					reasonableGeneral: '0',
					unreasonableKey: '0',
					unreasonableGeneral: '0',
					unreasonableForKey: '0%',
					unreasonableForGeneral: '0%',
					workOrderId: '',enterpriseDate:''
				},
				projectCounts: {
					zero: 0,
					one: 0
				}, //统计一般项和关键项
				heprojectCounts: {
					zero: 0,
					one: 0
				}, //统计一般项和关键项
				groupLeaderSign: '',
				teamMemberslSign: '',
				observerSign: '',
				enterpriseSign: '',
				remark: '',
				sociaCreditCode: '',
				workOrderId: '',
				foodDate: {
					year: '',
					month: '',
					day: ''
				},
				editStatus: 'ADD',
				onloadTag: '',
			}
		},
		props: {

			uploadUrl: {
				type: String,
				default: "https://8954wg323mw0.vicp.fun/app/upload/uploadFile"
			},

		},
		onLoad(options) {


			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);

				this.equipment.workOrderId = workOrderId;
				this.editStatus = options.editStatus;
				this.getMedicalInfo(workOrderId);
			} else {

				if (options.equipment) {
					const equipment = JSON.parse(decodeURIComponent(options.equipment));

					const orderid = decodeURIComponent(options.workOrderId);

					this.equipment = equipment;
					this.equipment.workOrderId = orderid;

				}
			}

			this.getProjectApi()
			this.getformatApi()
			this.getMedicalDict('mode_of_operation')
			this.getMedicalDict('medical_check_context')
			this.getMedicalDict('medical_check_to')

			this.getMedicalDict('medical_check_type')
		},
		computed: {
			// 判断是否是空白页
			isBlankPage() {
				const dataPages = Math.ceil(this.sourceData.length / this.pageSize)
				return this.curPageNum > dataPages
			},
			totalCheckItems() {
				return this.sourceData.length;
				// return this.sourceData.filter(item => item.delFlag === 1).length
			},
			unqualifiedItems() {
				return this.sourceData.filter(item => [2, 3].includes(item.delFlag)).length
			},
			processedData() {
				// 合理缺项统计
				const reasonableKeyCount = this.reasonableList.filter(v => v.project === "0").length;
				const reasonableGeneralCount = this.reasonableList.filter(v => v.project === "1").length;

				// 不符合项统计
				const unreasonableKey = this.verifyRecords.filter(v => v.project === "0").length;
				const unreasonableGeneral = this.verifyRecords.filter(v => v.project === "1").length;

				// 计算百分比（安全处理分母）
				const total = this.rawData.length || 1;
				const unreasonableForKey = ((unreasonableKey / total) * 100 || 0).toFixed(1) * 100 + "%";
				const unreasonableForGeneral = ((unreasonableGeneral / total) * 100 || 0).toFixed(1) * 100 + "%";

				return [{
						项目: '确认的合理缺项',
						关键项: '关键项',
						结果: `关键项缺失 ${reasonableKeyCount} 项`,
						rowspan: 2
					},
					{
						项目: '确认的合理缺项',
						关键项: '一般项',
						结果: `一般项缺失 ${reasonableGeneralCount} 项`,
						rowspan: 0
					},
					{
						项目: '不符合项',
						关键项: '关键项',
						结果: `关键项不符合 ${unreasonableKey} 项`,
						rowspan: 2
					},
					{
						项目: '不符合项',
						关键项: '一般项',
						结果: `一般项不符合 ${unreasonableGeneral} 项`,
						rowspan: 0
					},
					{
						项目: '不符合项占比',
						关键项: '关键项目不符合要求的项目数比例',
						结果: `占比 ${unreasonableForKey}`,
						rowspan: 2
					},
					{
						项目: '不符合项占比',
						关键项: '一般项目不符合要求的项目数比例',
						结果: `占比 ${unreasonableForGeneral}`,
						rowspan: 0
					}
				];
			}
		},
		// 在数据更新时调用统计方法
		watch: {

		},
		methods: {
			getFileName(fullPath) {
				if (!fullPath) return ''
				// 同时处理Windows和Linux路径分隔符
				const separator = fullPath.includes('/') ? '/' : '\\'
				return fullPath.split(separator).pop()
			},
			// 编辑描述
			editDescription(index) {
				uni.showModal({
					title: '填写备注',
					editable: true,
					content: this.verifyRecords[index].remarks || '',
					success: (res) => {
						if (res.confirm) {
							this.$set(this.verifyRecords[index], 'remarks', res.content)
						}
					}
				})
			},
			// 编辑描述
			editDescription2(index) {
				uni.showModal({
					title: '填写备注',
					editable: true,
					content: this.reasonableList[index].remarks || '',
					success: (res) => {
						if (res.confirm) {
							this.$set(this.reasonableList[index], 'remarks', res.content)
						}
					}
				})
			},
			// 修改后的上传方法
			onUpload(index) {
				this.onloadTag = 'verifyRecords'
				this.currentItem = index; // 直接保存索引值
				this.$refs.lFile.upload({
					url: this.uploadUrl,
					name: 'file'
				});
			},
			// 修改后的上传方法
			onUpload2(index) {
				this.onloadTag = 'reasonableList'
				this.currentItem = index; // 直接保存索引值
				this.$refs.lFile.upload({
					url: this.uploadUrl,
					name: 'file'
				});
			},

			// 修改后的成功回调
			onSuccess(res) {
				console.log('上传响应:', res);
				if (typeof this.currentItem === 'number') {
					try {
						const response = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;

						if (response.code === 0) {
							// 正确获取URL路径
							const fileUrl = response.data;


							if (this.onloadTag === 'verifyRecords') {
								// 使用Vue.set确保响应式更新
								this.$set(this.verifyRecords, this.currentItem, {
									...this.verifyRecords[this.currentItem],
									fileInfo: fileUrl
								});
							} else if (this.onloadTag === 'reasonableList') {
								// 使用Vue.set确保响应式更新
								this.$set(this.reasonableList, this.currentItem, {
									...this.reasonableList[this.currentItem],
									fileInfo: fileUrl
								});
							}
							uni.showToast({
								title: '上传成功'
							});

							// 强制更新视图（可选）
							this.$forceUpdate();
						}
					} catch (e) {
						console.error('解析响应数据失败:', e);
						uni.showToast({
							title: '数据处理失败',
							icon: 'none'
						});
					}
				}
			},

			updateEquipmentStats() {

				console.log(JSON.stringify(this.reasonableList))

				console.log(JSON.stringify(this.verifyRecords))
				// 合理缺项统计
				this.equipment.reasonableKey = this.reasonableList.filter(v => v.project === "0").length.toString();
				this.equipment.reasonableGeneral = this.reasonableList.filter(v => v.project === "1").length.toString();

				// 不符合项统计
				const unreasonableKey = this.verifyRecords.filter(v => v.project === "0").length;
				const unreasonableGeneral = this.verifyRecords.filter(v => v.project === "1").length;
				this.equipment.unreasonableKey = unreasonableKey.toString();
				this.equipment.unreasonableGeneral = unreasonableGeneral.toString();

				// 计算百分比（确保分母不为零）
				const total = this.rawData.length || 1; // 避免除以0
				this.equipment.unreasonableForKey = ((unreasonableKey / total) * 100 || 0).toFixed(1) + "%";
				this.equipment.unreasonableForGeneral = ((unreasonableGeneral / total) * 100 || 0).toFixed(1) + "%";

				this.$nextTick(() => {
					this.$forceUpdate(); // 强制组件重新渲染
				});
			},
			// 获取医疗器械工单详情
			async getMedicalInfo(orderId) {

				const id = {
					workOrderId: orderId
				}
				const res = await medicalGetInfo(id);
				if (res.code === 0) {
					console.log(res.data);
					this.equipment = res.data;
					// 在 data 或 methods 中处理
					this.reasonableList = res.data.fuhe.map(item => ({
						...item,
						clause: `${item.term} ${item.title}` // 使用模板字符串拼接
					}));
					this.verifyRecords = res.data.bufuhe.map(item => ({
						...item,
						clause: `${item.term} ${item.title}` // 使用模板字符串拼接
					}));
					//	this.equipment.reasonableList=this.reasonableList;
					//this.equipment.verifyRecords=res.data.bufuhe;
				}
			},
			modeChange(value) {
				console.log("e")
				console.log(value)
			},
			// 生成提交数据
			generateSubmitData() {
				//fuhe: [], //符合缺陷项目this.reasonableList
				//bufuhe: [], //不符合项目this.verifyRecords

				this.equipment.fuhe = this.reasonableList;
				this.equipment.bufuhe = this.verifyRecords;
				this.equipment.reasonableKey = this.reasonableList.filter(v => v.project === "0").length, //合理缺项-关键
					this.equipment.reasonableGeneral = this.reasonableList.filter(v => v.project === "1").length, //合理缺项-一般
					this.equipment.unreasonableKey = this.verifyRecords.filter(v => v.project === "0").length, //不合理缺项-关键
					this.equipment.unreasonableGeneral = this.verifyRecords.filter(v => v.project === "1")
					.length, //不合理缺项-一般
					this.equipment.unreasonableForKey = ((this.verifyRecords.filter(v => v.project === "0").length / this
							.rawData.length) *
						100 || 0).toFixed(1) * 100 + "%", //关键项目不符合比例
					this.equipment.unreasonableForGeneral = ((this.verifyRecords.filter(v => v.project === "1").length /
						this.rawData
						.length) * 100 || 0).toFixed(1) * 100 + "%", //一般项目不符合比例
					this.equipment.createBy = "管理员" //创建者
			},
			handleSignListUpdate(updatedList) {
				this.parentSignList = updatedList // 接收子组件传递的数据[2,9](@ref)
			},
			async showHePicker() {
				try {
					const type = {
						type: "3"
					};
					const res = await addResultList(type);

					if (res.code === 0) {
						this.rawData = res.data;

						// 生成带term和title的组合选项
						this.termList = res.data.map(item => ({
							text: `${item.term} ${item.title}`, // 组合显示
							value: JSON.stringify({ // 值保存两个字段
								term: item.term,
								title: item.title
							})
						}));

						// 默认选中第一个
						if (this.termList.length > 0) {
							this.selectedTerm = this.termList[0].value;
							this.filterData();
						}

						this.$refs.hePopup.open();
					}
				} catch (error) {
					uni.showToast({
						title: '加载条款失败',
						icon: 'none'
					});
				}
			},
			// 取消操作
			handleCancel() {
				this.$refs.termPopup.close()
			}, // 取消操作
			handleCancel2() {
				this.$refs.hePopup.close()
			},
			// 提交操作
			async handleSubmit() {
				try {
					// 获取当前表格所有数据（包含remarks）
					const allRecords = this.filteredData.map(item => ({
						term: item.term,
						title: item.title,
						context: item.context,
						remarks: item.remarks,
						templateId: item.templateId,
						project: item.project
					}));


					// 转换为verifyRecords结构
					const newRecords = allRecords.map(item => ({
						clause:item.term+item.title, // 条款号（显示title）
						remarks: item.remarks, // 描述（显示remarks）
						term: item.term, // 保留章节信息（如果需要）
						templateId: item.templateId,
						context: item.context,
						fileInfo: "", // 初始化附件状态
						time: new Date().toLocaleDateString(), // 添加时间
						project: item.project //0=关键项、1=一般项
					}));

					// 更新verifyRecords（Vue响应式更新）
					this.verifyRecords = [
						...this.verifyRecords,
						...newRecords
					];

					// 关闭弹窗
					this.$refs.termPopup.close();

					console.log("this.verifyRecords" + this.verifyRecords)
					uni.showToast({
						title: '添加成功'
					});

				} catch (error) {
					console.error('提交失败', error);
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					});
				}
			},
			async handleHeSubmit() {
				try {
					// 获取当前表格所有数据（包含remarks）
					const allRecords = this.filteredData.map(item => ({
						term: item.term,
						title: item.title,
						context: item.context,
						remarks: item.remarks,
						templateId: item.templateId,
						project: item.project //0=关键项、1=一般项
					}));


					// 转换为verifyRecords结构
					const newRecords = allRecords.map(item => ({
						clause: item.term+item.title, // 条款号（显示title）
						remarks: item.remarks, // 描述（显示remarks）
						term: item.term, // 保留章节信息（如果需要）
						templateId: item.templateId,
						context: item.context,
						fileInfo: "", // 初始化附件状态
						time: new Date().toLocaleDateString(), // 添加时间
						project: item.project //0=关键项、1=一般项
					}));

					// 更新reasonableList（Vue响应式更新）
					this.reasonableList = [
						...this.reasonableList,
						...newRecords
					];

					// 关闭弹窗
					this.$refs.hePopup.close();
					console.log('格式化后的数组:', JSON.stringify(this.reasonableList, null, 2));
					uni.showToast({
						title: '添加成功'
					});

				} catch (error) {
					console.error('提交失败', error);
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					});
				}
			},
			// 处理选择器变化
			handleTermChange(e) {
				this.selectedTerm = e;
				this.filterData();
			},
			getFilteredData(term) {
				return this.originalData.filter(item => item.term === term);
			},
			// 修改后的过滤方法
			filterData() {
				try {
					// 解析选中的值
					const {
						term,
						title
					} = JSON.parse(this.selectedTerm);

					this.filteredData = this.rawData.filter(
						item => item.term === term && item.title === title
					);

					if (this.filteredData.length === 0) {
						uni.showToast({
							title: '暂无相关数据',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('数据过滤错误:', e);
				}
			},
			// 修改showRolePicker方法
			async showRolePicker() {
				try {
					const type = {
						type: "3"
					};
					const res = await addResultList(type);

					if (res.code === 0) {
						this.rawData = res.data;

						// 生成带term和title的组合选项
						this.termList = res.data.map(item => ({
							text: `${item.term} ${item.title}`, // 组合显示
							value: JSON.stringify({ // 值保存两个字段
								term: item.term,
								title: item.title
							})
						}));

						// 默认选中第一个
						if (this.termList.length > 0) {
							this.selectedTerm = this.termList[0].value;
							this.filterData();
						}

						this.$refs.termPopup.open();
					}
				} catch (error) {
					uni.showToast({
						title: '加载条款失败',
						icon: 'none'
					});
				}
			},
			handleSignUpdate(list) {
				this.signList = list
			},
		
			handleCheckDateChange(date) {
				this.equipment.checkDate = date
			},
			//获取工单分类
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)

					console.log("res" + res)
					// 增加响应状态判断
					if (res.code === 0) {
						console.log('工单分类获取成功:')
						if (type === 'mode_of_operation') {
							this.operationList = res.data.map(item => ({
								text: item.label, // 注意字段名需与uni-data-select要求一致
								value: item.value
							}))
						} else if (type === 'medical_check_context') {
							this.contextList = res.data.map(item => ({
								text: item.label, // 注意字段名需与uni-data-select要求一致
								value: item.value
							}))
						} else if (type === 'medical_check_type') {
							this.typeList = res.data.map(item => ({
								text: item.label, // 注意字段名需与uni-data-select要求一致
								value: item.value
							}))
						} else if (type === 'medical_check_to') {
							this.toList = res.data.map(item => ({
								text: item.label, // 注意字段名需与uni-data-select要求一致
								value: item.value
							}))
						}


					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取分类失败',
						icon: 'none',
						duration: 2000
					})
				}
			},
			// 打开日期选择器
			openDatePicker() {
				this.tempDate = null; // 新增临时存储
				this.$refs.datePopup.open();
			},
			// 日期变化暂存
			handleDateChange(e) {
				this.tempDate = e ? new Date(e) : null;
			}, // 弹窗确认
			// 修改handleDialogConfirm方法
			handleDialogConfirm() {
				
				
				if (this.tempDate) {
					const year = this.tempDate.getFullYear();
					const month = (this.tempDate.getMonth() + 1).toString().padStart(2, '0');
					const day = this.tempDate.getDate().toString().padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					this.equipment.enterpriseDate = formattedDate;
console.log(this.equipment.enterpriseDate)
				}
				this.$refs.datePopup.close();
			},
			// 弹窗关闭
			handleDialogClose() {

				this.currentEditType = null;
				this.tempDate = null;
				this.$refs.datePopup.close();
			},
			// 获取当前日期字符串（用于初始化）
			getCurrentDateString() {
				const date = new Date();
				return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`;
			},

			// 日期确认处理
			handleDateConfirm(e) {
				const date = new Date(e);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');

				if (this.currentEditType) {
					const {
						type,
						field
					} = this.currentEditType;
					const target = type === 'check' ? this.checkDate : this.foodDate;

					// 更新全部日期字段
					target.year = year;
					target.month = month;
					target.day = day;


				}


				this.$refs.datePopup.close();
				this.currentEditType = null;

			},
			// 打开弹窗
			openPersonnelEditor() {
				this.$refs.personnelPopup.open()
			},

			// 确认保存
			handlePersonnelConfirm() {
				this.checkPersonnelNames = this.checkPersonnelList
					.filter(item => item.name.trim())
					.map(item => item.name)
					.join('、')
				this.$refs.personnelPopup.close()
			},

			// 添加人员
			addPersonnel() {
				this.checkPersonnelList.push({
					name: ''
				})
			},

			// 删除人员
			removePersonnel(index) {
				this.checkPersonnelList.splice(index, 1)
			},
			formatRadiochange(e) {
				this.formatRadio = e.detail.data.text;

			},
			projectRadiochange(e) {
				this.projectRadio = e.detail.data.text;

			},

			/**
			 * @param {Object} e
			 * 返回的签名地址 企业负责人签名
			 */
			signToUrl4(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)

				this.equipment.enterpriseSign = response.data;

			},



			// 提交方法
			submitForm(status) {
				this.equipment.auditStatus = status;
				if (this.editStatus == 'FALSE') {
					// 处理失败情况
					uni.showToast({
						title: '当前处于查看状态',
						icon: 'none'
					});
				}

				if (this.editStatus === 'EDIT') {
					this.UPDATE(status);
				}

				if (this.editStatus === 'ADD') {
					this.ADD(status);
				}
			},
			// 提交方法
			async ADD(status) {
				this.generateSubmitData();
				const res = await addMedical(this.equipment);

				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});
				// 关闭当前页面，跳转到工单页
				this.$closeAndRedirect({
				  url: '/pages/work/history/index'
				});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}


			},

			// 修改方法
			async UPDATE(status) {
				this.generateSubmitData();

				
				const res = await medicalUpdate(this.equipment);
				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});
					// 1.5秒后返回上一页
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						});
					}, 1500);
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},

			handleCheckChange(item) {
				console.log('选项变更:', item)
				// 这里可以添加自动保存逻辑
			},
			//获取经营业态方法
			async getformatApi() {
				try {
					const res = await getformat();
					if (res.code === 0) {
						// 格式化数据结构
						this.formatItem = res.data.map(item => ({
							text: item.label,
							value: item.value
						}));
						// 初始化默认选中项（可选）
						this.radio1 = this.formatItem[0]?.value || '';
					} else {
						throw new Error(res.msg || '获取业态数据异常');
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '业态数据加载失败',
						icon: 'none',
						duration: 2000
					});
					// 失败时设置默认空值
					this.formatItem = [];
				}
			},
			// 复选框经营业态方法处理
			handleCheckFormatChange(item) {
				console.log('选中值:', this.radio1);
				// 自动保存逻辑示例
				this.saveSelection({
					fieldType: item.type, // 业态或项目类型标识
					selectedValue: this.radio1
				});
			},
			// 复选框项目方法处理
			handleCheckProjectChange(item) {
				console.log('选中值:', this.radio1);

			},
			// 获取经营项目方法
			async getProjectApi() {
				try {
					const res = await getProject();
					if (res.code === 0) {
						// 数据结构转换
						this.projectItem = res.data.map(item => ({
							text: item.label,
							value: item.value
						}));
						// 初始化默认选中项（可选）
						this.radio1 = this.projectItem[0]?.value || '';
					} else {
						throw new Error(res.msg || '获取项目数据异常');
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '项目数据加载失败',
						icon: 'none',
						duration: 2000
					});
					// 失败时设置默认空值
					this.projectItem = [];
				}
			},

			/**
			 * @param {Object} e
			 * 组长
			 */
			signToUrl(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				// 1. 解析响应数据（假设 e.data 是 JSON 字符串）
				const response = JSON.parse(e.data)
				this.equipment.groupLeaderSign = response.data;
			},
			/**
			 * @param {Object} e
			 * 组员
			 */
			signToUrl2(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				console.log(response.data);
				this.equipment.teamMemberslSign = response.data;

			},
			/**
			 * @param {Object} e
			 * 观察员
			 */
			signToUrl3(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				this.equipment.observerSign = response.data;


			},
			// 添加签名列
			addSignColumn() {
				uni.showModal({
					title: '添加人员签名',
					content: '',
					editable: true, // 允许输入内容
					success: (res) => {
						if (res.confirm) {
							// 用户点击了“确定”
							const content = res.content || ''; // 获取输入的内容（如果允许输入）
							this.equipment.workOrderSignatureList.push({
								signature: '',
								signaturePosition: content, // 绑定输入的内容
								createBy: '系统管理员'
							});
						}
						// 用户点击“取消”则不做任何操作
					}
				});

			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.table-container {

		overflow-y: auto;
		margin: 15px 0;
	}

	.table-container2 {
		height: unset !important;
		/* 解除父容器高度限制 */
		min-height: 300px;
		/* 确保容器最小高度 */
		display: flex;
		/* 启用flex布局 */
		flex-direction: column;
		/* 纵向排列 */
	}

	/* 虚线容器 */
	.dashed {

		border: 2rpx dashed #0055ff;
		border-radius: 10rpx;
		background: #e5ecff;
		height: 50px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		margin: 15px;
		/* 垂直居中 */
		align-items: center;
	}

	/* 虚线容器 */
	.dashed2 {

		color: #ffffff;
		margin: 15px;
		border-radius: 10rpx;
		background: #3282ff;
		height: 50px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		/* 垂直居中 */
		align-items: center;
	}

	/* 移动端适配 */
	@media (max-width: 768px) {
		.mpopup-body {
			overflow-x: auto;

			&-thead,
			&-tbody {
				min-width: 800px;
			}
		}
	}

	.card-title {
		margin-bottom: 30px;
		font-size: 23px;
		margin-top: 20px;
		font-weight: bold;
		text-align: center;
		color: black;
	}

	.date-text {
		font-size: 14px;
		text-decoration: underline;
		padding: 4rpx 8rpx;
	}

	.custom-table {
		min-height: 300px;
		/* 最小高度保障[1](@ref) */

	}

	/* 标题行 */
	.title-row2 {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		margin-bottom: 68rpx;

		.title {
			font-size: 16rpx;
			color: #333;
			font-weight: 500;

		}

		.edit-btn {

			.btn-text {
				color: #2196F3;
				font-size: 16rpx;
				margin-left: 60px;
				margin-right: 16rpx;
			}


		}
	}

	/* 虚线容器 */
	.dashed3 {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;

		position: relative;

		&+.dashed-box {
			margin-top: 28rpx;
		}
	}

	/* 虚线容器 */
	.dashed4 {
		width: 100%;
		border: 2rpx dashed #0055ff;
		border-radius: 10rpx;
		background: #e5ecff;
		height: 120px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		/* 垂直居中 */
		align-items: center;
	}

	.uni-column {

		padding: 20px;
		background-color: #e9f1fe;
		height: 300px;
		margin-top: 10px;
		margin-bottom: 20%;
		border-radius: 10px;
	}

	/* 弹窗容器 */
	.custom-popup {
		width: 85vw;
		max-width: 650rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
	}

	/* 选择器样式 */
	.term-picker {
		border: 1rpx solid #e5e5e5;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
	}

	.picker-label::after {
		content: '▼';
		float: right;
		color: #666;
	}

	/* 表格容器 */
	.table-container {
		max-height: 60vh;

		.term-table {
			font-size: 28rpx;

			.title-cell {
				font-weight: bold;
				color: #2d8cf0;
			}

			.content-cell {
				height: 180rpx;

				scroll-view {
					height: 100%;
					line-height: 1.6;
				}
			}
		}
	}

	/* 取消按钮 */
	.cancel {
		background: #f0f0f0;
		color: #666;
		margin: 10px;
	}

	/* 提交按钮 */
	.submit {
		background: #007AFF;
		color: white;
		margin: 10px;
	}

	/* 使表格更紧凑 */
	.table-container uni-table {
		font-size: 24rpx;

		uni-th,
		uni-td {
			padding: 12rpx 8rpx;
		}

		uni-td {
			vertical-align: top;
		}
	}

	/* 虚线容器 */
	.dashed-box_confirm {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;
		margin-bottom: 40px;
		position: relative;

		&+.dashed-box {
			margin-top: 28rpx;
		}
	}

	.custom-title {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 10px;
		/* 保持原有下边距 */

	}

	.custom-dateText {
		display: flex;
		margin: 20px;
		justify-content: flex-end;
		/* 子元素居左 */
	}

	.custom-text3 {
		border-bottom: 1px solid #000;
		padding-bottom: 2px;
		padding-left: 10px;
		color: #0055ff;
		font-size: 16px;

		font-weight: bold;
		padding-right: 10px;
		margin-left: 4px;
		margin-right: 4px;
	}

	/* 虚线容器 */
	.dashed-box3 {
		width: 100%;
		border: 2rpx dashed #0055ff;
		border-radius: 10rpx;
		background: #e5ecff;
		height: 120px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		/* 垂直居中 */
		align-items: center;
	}

	/* 虚线容器 */
	.dashed-box2 {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;
		margin-bottom: 40px;
		position: relative;

		&+.dashed-box {
			margin-top: 28rpx;
		}



	}

	.titel-name {
		flex: 0 0 160px;
		display: flex;
		align-items: center;
		justify-content: center;

	}

	/* 添加点击样式 */
	.clickable-cell {
		color: #007AFF;
		text-decoration: underline;
		cursor: pointer;
	}
	.centered-input {
		width: 100%;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		/* 保持与高度一致 */
		border-radius: 12rpx;
	}
	
</style>